
import agent from 'server';
import { Form, Input, Modal } from 'antd';
import ICapability from 'components/capability/interfaces/ICapability';
import Controller from "Controller";
import React from 'react';
import useVisible from 'tools/hooks/useVisible';


/** 设置 */
export const setUp: ICapability<undefined> = {
    id: 'setUp',
    title: '设置',
    useExpand: () => {

        const controller = Controller.instance

        const threeController = Controller.instance.useMemo(s => s.threeController, []);

        const [form] = Form.useForm();

        const { isOpen, onCancel, onOpen } = useVisible();

        const onClick = onOpen;

        const onOk = React.useCallback(async () => {
            await controller.run(async s => {
                s.project = { ...s.project, ...await form.validateFields() }
                if (s.project.path) {
                    window.localStorage.setItem('$$/project/path', s.project.path);
                    threeController.recover((await agent.get('/api/project/ldte').over()).body);
                } else {
                    window.localStorage.removeItem('$$/project/path');
                }
            })
            onCancel();
        }, [controller, form, onCancel, threeController]);

        const element = React.useMemo(() => {
            return (
                <Modal
                    title="设置项目"
                    onCancel={onCancel}
                    open={isOpen}
                    onOk={onOk}
                >
                    <Form
                        layout="vertical"
                        form={form}
                    >
                        <Form.Item
                            label="工程地址"
                            name="path"
                            rules={[
                                { required: true, message: '请输入工程地址' }
                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Form>
                </Modal>
            )
        }, [form, isOpen, onCancel, onOk])

        React.useEffect(() => {
            if(isOpen){
                form.resetFields();
                form.setFieldsValue(controller.state.project);
            }
        }, [controller, form, isOpen])

        return {
            onClick,
            element,
        }
    }
}